// [DELETE]feature-t1-1.8.3-privilege
/* eslint-disable react/no-danger */
import React from 'react';
import { Table, Tooltip, Button, Switch, Input, message, Popover } from 'antd';
import { history } from 'umi'
import authHelpr from '@/utils/auth/helper';
import { BaseWrapper } from '../components';
import { updateAuthStatus } from '../services';
import { TERMINAL, AUDIT, AUTH, GRADE, STATUS } from '../constant';

const { checkCode } = authHelpr;
const { Search } = Input;

// 网页端不可启用、禁用的菜单code
const WEB_DISABLED_CODE = ['portal', 'portal:mine'];

const SwitchItem = ({ record, onOk }) => {
    const [loading, setLoading] = React.useState(false);

    const handleCheck = async flag => {
        setLoading(true);
        const res = await updateAuthStatus({
            code: record && record.code,
            status: flag ? 0 : 1
        });
        setLoading(false);
        const { code, msg } = res;
        if (code === 10000) {
            if (onOk) {
                onOk();
            }
        } else {
            message.error(msg);
        }
    };

    return (
        <Switch
            loading={loading}
            disabled={WEB_DISABLED_CODE.includes(record?.code)}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            checked={record && record.status === 0}
            onClick={handleCheck}
        />
    );
};

const AuthBox = ({ terminalType, loading, dataSource = [], onOk }) => {
    const [selectedRows, setSelectedRows] = React.useState([]);

    const [query, setQuery] = React.useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);

    const [expandedKeys, setExpandedKeys] = React.useState([]); // 存储选中的变量
    const [oldExpandedKeys, setOldExpandedKeys] = React.useState([]); // 存储用户操作的展开变量
    const [open, setOpen] = React.useState(false); // 区分启用和表单筛选搜索的中间变量

    const rowSelection = {
        onChange: (selectedRowKeysTemp, selectedRowsTemp) => {
            // console.log(`selectedRowKeys: ${selectedRowKeysTemp}`, 'selectedRows: ', selectedRowsTemp);
            setSelectedRowKeys(selectedRowKeysTemp);
            setSelectedRows(selectedRowsTemp);
        },
        getCheckboxProps: record => ({
            disabled: record.auditStatus !== 2
        }),
        selectedRowKeys
    };
    const handleEdit = arr => {
        // console.log(dataSource);
        if (arr && arr.length > 0) {
            localStorage.setItem('authEditTitle', TERMINAL[terminalType]);
            localStorage.setItem('authEdit', JSON.stringify(arr));
            history.push({
                pathname: '/office/personnelManagement/organization/authedit'
            });
        } else {
            message.warn('请选择需要编辑的功能');
        }
    };

    const handleEditBatch = () => {
        handleEdit(selectedRows);
    };

    const handleTableChange = async (_, filters) => {
        const { type = [], auditStatus = [], gradeType = [] } = filters;
        setQuery({
            ...query,
            terminalType,
            types: type,
            auditStatuses: auditStatus,
            gradeTypes: gradeType
        });
        setOpen(true);
    };

    const handleSearch = value => {
        if (value.trim()) {
            setQuery({
                ...query,
                terminalType,
                name: value.trim()
            });
        } else {
            setQuery({
                ...query,
                name: ''
            });
        }
        setOpen(true);
    };
    const handleExpandedRowsChange = expandedRows => {
        setExpandedKeys(expandedRows);
        setOldExpandedKeys(expandedRows);
    };
    // 获取数据id 用于展开用
    const getDataSourceId = treeData => {
        const arr = [];
        const filterTree = tree => {
            tree.forEach(({ children, id }) => {
                arr.push(id);
                if (children && children.length > 0) {
                    filterTree(children);
                }
            });
        };
        filterTree(treeData);
        return arr;
    };

    React.useEffect(() => {
        if (query) {
            if (open) {
                setExpandedKeys([]);
            } else {
                setExpandedKeys(oldExpandedKeys);
            }
            const { name = '', auditStatuses = [], gradeTypes = [], types = [] } = query;
            if (name !== '' || auditStatuses.length > 0 || gradeTypes.length > 0 || types.length > 0) {
                setExpandedKeys(getDataSourceId(dataSource));
            }
        }
    }, [query, dataSource]);
    React.useEffect(() => {
        if (onOk && query) {
            onOk(query, terminalType);
            setSelectedRowKeys([]);
            setSelectedRows([]);
        }
    }, [query]);
    const columns = [
        {
            title: '功能',
            key: 'name',
            dataIndex: 'name',
            render: (text, record) => {
                if (query && query.name) {
                    const value = query.name.trim();
                    const arr = text.split(value);
                    const html = arr.join(`<span style="color: #f5222d;">${value}</span>`);
                    return record.description ? (
                        <Popover placement="top" title={<strong>功能简介</strong>} content={record.description}>
                            <span dangerouslySetInnerHTML={{ __html: html }} />
                        </Popover>
                    ) : (
                        <span dangerouslySetInnerHTML={{ __html: html }} />
                    );
                }
                return record.description ? (
                    <Popover placement="top" title={<strong>功能简介</strong>} content={record.description}>
                        {text}
                    </Popover>
                ) : (
                    text
                );
            }
        },
        {
            title: '类型',
            key: 'type',
            dataIndex: 'type',
            filters: [
                { text: AUTH['1'], value: 1 },
                { text: AUTH['2'], value: 2 },
                { text: AUTH['3'], value: 3 }
            ],
            render: text => AUTH[text] || ''
        },
        {
            title: '审批',
            key: 'auditStatus',
            dataIndex: 'auditStatus',
            filters: [
                // { text: AUDIT['0'], value: 0 },
                { text: AUDIT['1'], value: 1 },
                { text: AUDIT['2'], value: 2 }
                // { text: AUDIT['3'], value: 3 }
            ],
            render: text => AUDIT[text] || ''
        },
        {
            title: '等级',
            key: 'gradeType',
            dataIndex: 'gradeType',
            filters: [
                { text: GRADE['1'], value: 1 },
                { text: GRADE['2'], value: 2 },
                { text: GRADE['3'], value: 3 }
            ],
            render: text => {
                if (text === 3) {
                    return <span style={{ color: '#f5222d' }}>{GRADE[text]}</span>;
                }
                return GRADE[text] || '';
            }
        },
        {
            title: '授权',
            key: 'dutyNumber',
            dataIndex: 'dutyNumber'
        },
        {
            title: '状态',
            key: 'status',
            dataIndex: 'status',
            render: text => STATUS[text] || ''
        },
        {
            title: '操作',
            key: 'operation',
            dataIndex: 'operation',
            width: 130,
            render: (text, record) => (
                <>
                    {checkCode('office:orgs:authority:edit') && (
                        <Tooltip title="编辑">
                            <Button
                                type="link"
                                icon="edit"
                                disabled={record.auditStatus !== 2}
                                onClick={() => handleEdit([record])}
                                style={{ marginRight: 8 }}
                            />
                        </Tooltip>
                    )}

                    {/* {record.type !== 2 && record.type !== 1 && ( */}
                    {checkCode('office:orgs:authority:status') && (
                        <SwitchItem
                            record={record}
                            onOk={() => {
                                setOpen(false);
                                setQuery({
                                    ...query
                                });
                            }}
                        />
                    )}
                    {/* )} */}
                </>
            )
        }
    ];
    console.log(dataSource, 'dataSource');
    return (
        <BaseWrapper title={TERMINAL[terminalType] || ''} style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
                <div className="searchControls">
                    {checkCode('office:orgs:authority:batch') && (
                        <Button type="primary" onClick={handleEditBatch}>
                            批量操作
                        </Button>
                    )}
                </div>
                <Search placeholder="搜索功能关键词" onSearch={handleSearch} style={{ width: 200 }} allowClear />
            </div>
            <Table
                defaultExpandAllRows
                columns={columns}
                loading={loading}
                rowSelection={rowSelection}
                dataSource={dataSource}
                expandedRowKeys={expandedKeys}
                onChange={handleTableChange}
                rowKey="id"
                pagination={false}
                onExpandedRowsChange={handleExpandedRowsChange}
            />
        </BaseWrapper>
    );
};

AuthBox.defaultProps = {
    terminalType: 0,
    loading: false,
    dataSource: []
};

export default AuthBox;
